package com.zunipe.trainticketsystem.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.zunipe.trainticketsystem.R;
import com.zunipe.trainticketsystem.TrainInfoActivity;
import com.zunipe.trainticketsystem.database.entity.Train;
import com.zunipe.trainticketsystem.database.handler.TrainHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TrainListAdapter extends RecyclerView.Adapter<TrainListAdapter.TrainViewHolder> {
    private final TrainHandler trainHandler;
    private List<Train> trainList;
    private Map<String, ArrayList<Train>> trainMapOrderByTrainNumber;
    private List<String> trainNumberList;
    private Context context;

    public TrainListAdapter() {
        trainHandler = new TrainHandler();
        trainList = trainHandler.getTrainList();

        // 将获取到的车票信息按照车次号分类，方便展示各种等级座位的车票数
        trainMapOrderByTrainNumber = new HashMap<>();
        trainNumberList = new ArrayList<>();
        trainList.forEach(train -> {
            String trainNumber = train.getTrainNumber();
            if (!trainMapOrderByTrainNumber.containsKey(trainNumber)) {
                trainMapOrderByTrainNumber.put(trainNumber, new ArrayList<>());
                trainNumberList.add(trainNumber);
            }
            ArrayList<Train> trains = trainMapOrderByTrainNumber.get(trainNumber);
            assert trains != null;
            trains.add(train);
        });
    }

    public void updateUI() {
        trainList = trainHandler.getTrainList();

        trainMapOrderByTrainNumber.clear();
        trainNumberList.clear();
        trainList.forEach(train -> {
            String trainNumber = train.getTrainNumber();
            if (!trainMapOrderByTrainNumber.containsKey(trainNumber)) {
                trainMapOrderByTrainNumber.put(trainNumber, new ArrayList<>());
                trainNumberList.add(trainNumber);
            }
            ArrayList<Train> trains = trainMapOrderByTrainNumber.get(trainNumber);
            assert trains != null;
            trains.add(train);
        });
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public TrainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.train_item_layout, parent, false);
        context = parent.getContext();
        return new TrainViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TrainViewHolder holder, int position) {
        String trainNumber = trainNumberList.get(position);
        ArrayList<Train> trains = trainMapOrderByTrainNumber.get(trainNumber);
        if (trains != null) {
            for (int i = 0; i < trains.size(); ++i) {
                Train train = trains.get(i);
                double price = Double.MAX_VALUE;
                price = Math.min(train.getPrice(), price);

                switch (train.getType()) {
                    case "二等":
                        holder.tvSecondType.setText(context.getString(R.string.second_type, train.getCount()));
                        break;
                    case "一等":
                        holder.tvFirstType.setText(context.getString(R.string.first_type, train.getCount()));
                        break;
                    case "特等":
                        holder.tvSpecialType.setText(context.getString(R.string.special_type, train.getCount()));
                        break;
                    case "无座":
                        holder.tvNoneType.setText(context.getString(R.string.none_type, train.getCount()));
                        break;
                }

                if (i == trains.size() - 1) { // 最后一次遍历才设置，防止重复设置
                    holder.tvPlaceOfStart.setText(train.getPlaceOfStart());
                    holder.tvPlaceOfEnd.setText(train.getPlaceOfEnd());
                    holder.tvStartTime.setText(train.getStartTime());
                    holder.tvEndTime.setText(train.getEndTime());
                    holder.tvTrainNumber.setText(train.getTrainNumber());
                    holder.tvPrice.setText(context.getString(R.string.minimum_price, price));
                }
            }
        }
        holder.root.setOnClickListener(v -> {
            Intent intent = new Intent(context, TrainInfoActivity.class);
            intent.putExtra("trainNumber", trainNumber);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return trainNumberList.size();
    }

    public static class TrainViewHolder extends RecyclerView.ViewHolder {
        View root;
        TextView tvPlaceOfStart;
        TextView tvPlaceOfEnd;
        TextView tvStartTime;
        TextView tvEndTime;
        TextView tvTrainNumber;
        TextView tvUseTime;
        TextView tvPrice;
        TextView tvSecondType;
        TextView tvFirstType;
        TextView tvSpecialType;
        TextView tvNoneType;

        public TrainViewHolder(@NonNull View itemView) {
            super(itemView);
            root = itemView;
            tvPlaceOfStart = itemView.findViewById(R.id.tv_place_of_start);
            tvPlaceOfEnd = itemView.findViewById(R.id.tv_place_of_end);
            tvStartTime = itemView.findViewById(R.id.tv_start_time);
            tvEndTime = itemView.findViewById(R.id.tv_end_time);
            tvTrainNumber = itemView.findViewById(R.id.tv_train_number);
            tvUseTime = itemView.findViewById(R.id.tv_use_time);
            tvPrice = itemView.findViewById(R.id.tv_price);
            tvSecondType = itemView.findViewById(R.id.tv_second_type);
            tvFirstType = itemView.findViewById(R.id.tv_first_type);
            tvSpecialType = itemView.findViewById(R.id.tv_special_type);
            tvNoneType = itemView.findViewById(R.id.tv_none_type);
        }
    }
}
